package com.wang.service.impl;

import com.wang.bean.SysUserEntity;
import com.wang.config.ShiroUtils;
import com.wang.mapper.SysUserMapper;
import com.wang.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUserEntity selectOne(String userName) {
        return sysUserMapper.selectOne(userName);
    }

    @Override
    public SysUserEntity selectOneById(Long user_id) {
        return sysUserMapper.selectOneById(user_id);
    }

    @Override
    public void updatethisuser(SysUserEntity sysUserEntity) {
        sysUserMapper.updatethisuser(sysUserEntity);
    }

    @Override
    public List<SysUserEntity> selectLot(String userName) {
        return sysUserMapper.selectLot(userName);
    }

    @Override
    public List<SysUserEntity> selectLot1(SysUserEntity sysUserEntity) {
        return sysUserMapper.selectLot1(sysUserEntity);
    }

    @Override
    public void insertuser(SysUserEntity sysUserEntity) {
        sysUserMapper.insertuser(sysUserEntity);
    }

    @Override
    public void deleteuserbyid(Long user_id) {
        sysUserMapper.deleteuserbyid(user_id);
    }

    @Override
    public void updatepassword(SysUserEntity sysUserEntity) {
        sysUserMapper.updatepassword(sysUserEntity);
    }

    @Override
    public String importUser(String fileName, MultipartFile file) throws Exception {

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return "格式错误！";
        }
        //System.out.println("第1个判断正确");

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        //System.out.println("第2个判断正确");

        System.out.println(isExcel2003);
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        //System.out.println("第3个判断正确");

        Sheet sheet = wb.getSheetAt(0); //获取excel表的第一页
        if (sheet == null) {
            //System.out.println("表为空！");
            return "表为空！";
        }
        //System.out.println("第4个判断正确");

        SysUserEntity sysUserEntity;

        String rowError = "";

        List<SysUserEntity> sysUserEntities = new ArrayList<>();

        int cw = 0, cg = 0, gx = 0;
        for (int r = 2; r <= sheet.getLastRowNum(); r++) {  //r = 1 表示从第2行开始循环 如果你的第2行开始是数据
            //System.out.println("------------------------------------------------------------------");
            Row row = sheet.getRow(r);//通过sheet表单对象得到 行对象
            if (row == null) {
                rowError += "第" + (r + 1) + "行为空；\n";
                cw++;
                continue;
            }
            //System.out.println("第5个判断正确");

            sysUserEntity = new SysUserEntity();

            //用户ID
            Long userId = null;
            if (row.getCell(0) == null) {
                rowError += "第" + (r + 1) + "行，用户ID未填写；";
                //System.out.println("第" + (r + 1) + "行，用户ID未填写；");
                //continue;
            } else {
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                String tempId =row.getCell(0).getStringCellValue();//得到每一行第一个单元格的值，i+1行
                if (tempId == null){
                    rowError += "第" + (r + 1) + "行，用户ID转换失败；";
                    continue;
                }
                try{
                    userId = Long.parseLong(tempId);
                } catch (NumberFormatException e){
                    rowError += "第" + (r + 1) + "行，用户ID转换失败；";
                    //System.out.println("第" + (r + 1) + "行，用户ID转换失败；");
                    userId = null;
                }
                //System.out.println(userId);
                if (userId == null || userId == 0) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，用户ID未填写；";
                    //System.out.println("第" + (r + 1) + "行，用户ID未填写；");
                }
            }

            //用户名
            String userName = null;
            if (row.getCell(1) == null) {
                rowError += "第" + (r + 1) + "行，用户名未填写；\n";
                //System.out.println("第" + (r + 1) + "行，用户名未填写；");
                cw++;
                continue;
            } else {
                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                userName = row.getCell(1).getStringCellValue();
                //System.out.println(userName);
                if (userName == null || userName.isEmpty()) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，用户名未填写；";
                    //System.out.println("第" + (r + 1) + "行，用户名未填写；");
                }
            }

            //用户密码
            String userPassword = null;
            if (row.getCell(2) == null) {
                rowError += "第" + (r + 1) + "行，用户密码未填写；\n";
                //System.out.println("第" + (r + 1) + "行，用户密码未填写；");
                cw++;
                continue;
            } else {
                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                userPassword = row.getCell(2).getStringCellValue();
                //System.out.println(userPassword);
                if (userPassword == null || userPassword.isEmpty()) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，用户密码未填写；";
                    //System.out.println("第" + (r + 1) + "行，用户密码未填写；");
                }
            }

            //用户盐
            String userSalt = null;
            if (row.getCell(3) == null) {
                rowError += "第" + (r + 1) + "行，用户盐未填写；";
                //System.out.println("第" + (r + 1) + "行，用户盐未填写；");
                //continue;
            } else {
                row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                userSalt = row.getCell(3).getStringCellValue();
                //System.out.println(userSalt);
                if (userSalt == null || userSalt.isEmpty()) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，用户盐未填写；";
                    //System.out.println("第" + (r + 1) + "行，用户盐未填写；");
                }
            }

            //用户邮箱
            String userEmail = null;
            if (row.getCell(4) == null) {
                rowError += "第" + (r + 1) + "行，用户邮箱未填写；";
                //System.out.println("第" + (r + 1) + "行，用户邮箱未填写；");
                //continue;
            } else {
                row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                userEmail = row.getCell(4).getStringCellValue();
                //System.out.println(userEmail);
                if (userEmail == null || userEmail.isEmpty()) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，用户邮箱未填写；";
                    //System.out.println("第" + (r + 1) + "行，用户邮箱未填写；");
                }
            }

            //用户手机
            String userMobile = null;
            if (row.getCell(5) == null) {
                rowError += "第" + (r + 1) + "行，用户手机未填写；";
                //System.out.println("第" + (r + 1) + "行，用户手机未填写；");
                //continue;
            } else {
                row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                userMobile = row.getCell(5).getStringCellValue();
                //System.out.println(userMobile);
                if (userMobile == null || userMobile.isEmpty()) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，用户手机未填写；";
                    //System.out.println("第" + (r + 1) + "行，用户手机未填写；");
                }
            }

            //用户状态
            Integer userStatus = null;
            if (row.getCell(6) == null) {
                rowError += "第" + (r + 1) + "行，用户状态未填写；";
                //System.out.println("第" + (r + 1) + "行，用户状态未填写；");
                //continue;
            } else {
                row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                String tempStatus =row.getCell(6).getStringCellValue();//得到每一行第一个单元格的值，i+1行
                if (tempStatus == null){
                    rowError += "第" + (r + 1) + "行，用户状态转换失败；";
                    continue;
                }
                try{
                    userStatus = Integer.parseInt(tempStatus);
                } catch (NumberFormatException e){
                    rowError += "第" + (r + 1) + "行，用户状态转换失败；";
                    //System.out.println("第" + (r + 1) + "行，用户状态转换失败；");
                    cw++;
                    userStatus = null;
                }
                //System.out.println(userStatus);
                if (userStatus == null || userStatus == 0) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，用户状态未填写；";
                    //System.out.println("第" + (r + 1) + "行，用户状态未填写；");
                }
            }

            /*
            //创建者ID
            Long userCreateUserId = null;
            if (row.getCell(7) == null) {
                rowError += "第" + (r + 1) + "行，创建用户ID未填写；";
                System.out.println("第" + (r + 1) + "行，创建用户ID未填写；");
                //continue;
            } else {
                String tempCId = row.getCell(7).getStringCellValue();
                try{
                    userCreateUserId = Long.parseLong(tempCId);
                } catch (NumberFormatException e){
                    rowError += "第" + (r + 1) + "行，创建用户ID转换失败；";
                    System.out.println("第" + (r + 1) + "行，创建用户ID转换失败；");
                    userCreateUserId = null;
                }
                System.out.println(userCreateUserId);
                if (userCreateUserId == null || userCreateUserId == 0) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，创建用户ID未填写；";
                    System.out.println("第" + (r + 1) + "行，创建用户ID未填写；");
                }
            }

            //创建时间
            Date userDate = null;
            if (row.getCell(8) == null) {
                rowError += "第" + (r + 1) + "行，创建时间未填写；";
                System.out.println("第" + (r + 1) + "行，创建时间未填写；");
                //continue;
            } else {
                String tempDate = row.getCell(8).getStringCellValue();
                String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                try{
                    userDate = sdf.parse(tempDate);
                } catch (Exception e){
                    rowError += "第" + (r + 1) + "行，创建时间转换失败；";
                    System.out.println("第" + (r + 1) + "行，创建时间转换失败；");
                    userDate = null;
                }
                System.out.println(userDate);
                if (userDate == null) {//判断是否为空
                    rowError += "第" + (r + 1) + "行，创建时间未填写；";
                    System.out.println("第" + (r + 1) + "行，创建时间未填写；");
                }
            }
            */

            sysUserEntity.setUser_id(userId);
            sysUserEntity.setUsername(userName);
            if (userSalt == null || "".equals(userSalt)){
                userSalt = "123";
            }
            sysUserEntity.setSalt(userSalt);
            sysUserEntity.setPassword(ShiroUtils.sha256(userPassword,userSalt));
            sysUserEntity.setEmail(userEmail);
            sysUserEntity.setMobile(userMobile);
            if (userStatus == null){
                userStatus = 1;
            }
            if (userStatus != 1 || userStatus != 0){
                userStatus = 1;
            }
            sysUserEntity.setStatus(userStatus);
            sysUserEntity.setCreateTime(new Date());

            if (sysUserEntity.getUsername() == null){
                rowError += "第" + (r + 1) + "行，用户名为空，跳过；\n";
                cw++;
                continue;
            }
            if (sysUserEntity.getUser_id() != null){
                SysUserEntity sysUserEntity1 = sysUserMapper.selectOneById(sysUserEntity.getUser_id());
                SysUserEntity sysUserEntity2 = sysUserMapper.selectOne(sysUserEntity.getUsername());
                if (sysUserEntity1 != null){
                    rowError += "第" + (r + 1) + "行，ID为" + sysUserEntity.getUser_id() + "的用户已存在，跳过；\n";
                    cw++;
                    continue;
                }
                if (sysUserEntity2 != null){
                    rowError += "第" + (r + 1) + "行，用户名为" + sysUserEntity.getUsername() + "的用户已存在，跳过；\n";
                    cw++;
                    continue;
                }
                cg++;
                sysUserEntities.add(sysUserEntity);
            } else {
                if (sysUserMapper.selectOne(sysUserEntity.getUsername()) != null){
                    rowError += "第" + (r + 1) + "行，用户名为" + sysUserEntity.getUsername() + "的用户已存在，跳过；\n";
                    cw++;
                    continue;
                }
                cg++;
                sysUserEntities.add(sysUserEntity);
            }

            rowError += "\n";
        }

        for (SysUserEntity sysUserEntity1 : sysUserEntities){
            if (sysUserEntity1.getUser_id() == null){
                sysUserMapper.insertuserandid(sysUserEntity1);
            } else {
                sysUserMapper.insertuser(sysUserEntity1);
            }
        }

        is.close();
        return rowError += "成功"+cg+"条，失败"+cw+"条，共计"+(cw+cg)+"条";
    }

}
